import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';

class StorageUtil {
  static const String _tokenKey = 'access_token';
  static const String _tokenExpiryKey = 'token_expiry';
  static const String _userInfoKey = 'user_info';
  static const String _locationKey = 'cached_location';
  static const String _temperatureKey = 'cached_temperature';
  static const String _weatherDescKey = 'cached_weather_desc';
  static const String _weatherIconKey = 'cached_weather_icon';
  static const String _locationTimestampKey = 'location_timestamp';

  /// 保存 Token 和过期时间
  static Future<void> saveToken(String token, {Duration? expiryDuration}) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(_tokenKey, token);
    
    // 默认7天过期，可以根据后端返回的过期时间调整
    final expiry = DateTime.now().add(expiryDuration ?? const Duration(days: 7));
    await prefs.setInt(_tokenExpiryKey, expiry.millisecondsSinceEpoch);
  }

  /// 获取 Token
  static Future<String?> getToken() async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getString(_tokenKey);
  }

  /// 移除 Token（登出时调用）
  static Future<void> clearToken() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.remove(_tokenKey);
    await prefs.remove(_tokenExpiryKey);
    await prefs.remove(_userInfoKey);
  }

  /// 判断是否已登录且token未过期
  static Future<bool> isLoggedIn() async {
    final token = await getToken();
    if (token == null || token.isEmpty) {
      return false;
    }
    
    // 检查token是否过期
    final prefs = await SharedPreferences.getInstance();
    final expiryTimestamp = prefs.getInt(_tokenExpiryKey);
    if (expiryTimestamp == null) {
      return false;
    }
    
    final expiryTime = DateTime.fromMillisecondsSinceEpoch(expiryTimestamp);
    return DateTime.now().isBefore(expiryTime);
  }

  /// 检查token是否即将过期（1天内）
  static Future<bool> isTokenExpiringSoon() async {
    final prefs = await SharedPreferences.getInstance();
    final expiryTimestamp = prefs.getInt(_tokenExpiryKey);
    if (expiryTimestamp == null) {
      return true;
    }
    
    final expiryTime = DateTime.fromMillisecondsSinceEpoch(expiryTimestamp);
    final oneDayFromNow = DateTime.now().add(const Duration(days: 1));
    return expiryTime.isBefore(oneDayFromNow);
  }

  /// 保存用户信息
  static Future<void> saveUserInfo(Map<String, dynamic> userInfo) async {
    final prefs = await SharedPreferences.getInstance();
    // 使用 jsonEncode 而不是 toString()
    await prefs.setString(_userInfoKey, jsonEncode(userInfo));
  }

  /// 获取用户信息
  static Future<String?> getUserInfo() async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getString(_userInfoKey);
  }

  /// 保存位置和天气信息
  static Future<void> saveLocationWeather({
    required String address,
    required int temperature,
    required String weatherDescription,
    required String weatherIcon,
  }) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(_locationKey, address);
    await prefs.setInt(_temperatureKey, temperature);
    await prefs.setString(_weatherDescKey, weatherDescription);
    await prefs.setString(_weatherIconKey, weatherIcon);
    await prefs.setInt(_locationTimestampKey, DateTime.now().millisecondsSinceEpoch);
  }

  /// 获取缓存的位置信息
  static Future<String?> getCachedLocation() async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getString(_locationKey);
  }

  /// 获取缓存的天气信息
  static Future<Map<String, dynamic>?> getCachedWeather() async {
    final prefs = await SharedPreferences.getInstance();
    final temperature = prefs.getInt(_temperatureKey);
    final description = prefs.getString(_weatherDescKey);
    final icon = prefs.getString(_weatherIconKey);
    
    if (temperature != null && description != null && icon != null) {
      return {
        'temperature': temperature,
        'description': description,
        'icon': icon,
      };
    }
    return null;
  }

  /// 检查位置信息是否存在
  static Future<bool> hasLocationCache() async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.containsKey(_locationKey) && 
           prefs.containsKey(_temperatureKey) && 
           prefs.containsKey(_weatherDescKey) && 
           prefs.containsKey(_weatherIconKey);
  }

  /// 清除位置和天气缓存（退出app时调用）
  static Future<void> clearLocationWeatherCache() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.remove(_locationKey);
    await prefs.remove(_temperatureKey);
    await prefs.remove(_weatherDescKey);
    await prefs.remove(_weatherIconKey);
    await prefs.remove(_locationTimestampKey);
  }

  /// 获取位置缓存时间戳
  static Future<DateTime?> getLocationCacheTimestamp() async {
    final prefs = await SharedPreferences.getInstance();
    final timestamp = prefs.getInt(_locationTimestampKey);
    if (timestamp != null) {
      return DateTime.fromMillisecondsSinceEpoch(timestamp);
    }
    return null;
  }

  /// 通用存储方法 - 存储字符串
  static Future<void> setValue(String key, String value) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(key, value);
  }

  /// 通用获取方法 - 获取字符串
  static Future<String?> getValue(String key) async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getString(key);
  }

  /// 通用删除方法
  static Future<void> removeValue(String key) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.remove(key);
  }
}
